/**
 * 文件上传中间件
 * 处理文件上传、验证和存储
 */

const multer = require('multer');
const path = require('path');
const fs = require('fs');
const { v4: uuidv4 } = require('uuid');
const config = require('../config');

// 确保上传目录存在
const ensureDirectoryExists = (dirPath) => {
    if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath, { recursive: true });
    }
};

// 确保上传目录存在
ensureDirectoryExists(config.upload.gameFilePath);
ensureDirectoryExists(config.upload.thumbnailPath);

// 游戏文件存储配置
const gameStorage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, config.upload.gameFilePath);
    },
    filename: function(req, file, cb) {
        // 生成唯一文件名
        const uniqueSuffix = uuidv4();
        const ext = path.extname(file.originalname);
        cb(null, `game-${uniqueSuffix}${ext}`);
    }
});

// 缩略图存储配置
const thumbnailStorage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, config.upload.thumbnailPath);
    },
    filename: function(req, file, cb) {
        // 生成唯一文件名
        const uniqueSuffix = uuidv4();
        const ext = path.extname(file.originalname);
        cb(null, `thumbnail-${uniqueSuffix}${ext}`);
    }
});

// 文件过滤器
const fileFilter = (allowedTypes) => (req, file, cb) => {
    const ext = path.extname(file.originalname).toLowerCase();
    
    if (allowedTypes.includes(ext)) {
        cb(null, true);
    } else {
        cb(new Error(`不支持的文件类型: ${ext}，允许的类型: ${allowedTypes.join(', ')}`), false);
    }
};

// 游戏文件上传配置
const uploadGame = multer({
    storage: gameStorage,
    limits: {
        fileSize: config.upload.maxGameSize,
    },
    fileFilter: fileFilter(config.upload.allowedGameTypes)
});

// 缩略图上传配置
const uploadThumbnail = multer({
    storage: thumbnailStorage,
    limits: {
        fileSize: config.upload.maxThumbnailSize,
    },
    fileFilter: fileFilter(config.upload.allowedThumbnailTypes)
});

// 上传处理中间件
module.exports = {
    // 上传游戏文件
    uploadGameFile: uploadGame.single('gameFile'),
    
    // 上传缩略图
    uploadThumbnail: uploadThumbnail.single('thumbnail'),
    
    // 上传游戏和缩略图
    uploadGameFiles: [
        uploadGame.single('gameFile'),
        uploadThumbnail.single('thumbnail')
    ],
    
    // 处理Multer错误
    handleUploadError: (err, req, res, next) => {
        if (err instanceof multer.MulterError) {
            // Multer错误处理
            let message = '文件上传失败';
            
            if (err.code === 'LIMIT_FILE_SIZE') {
                message = '文件大小超出限制';
            }
            
            return res.status(400).json({
                success: false,
                message
            });
        }
        
        // 处理自定义错误信息
        if (err.message && err.message.includes('不支持的文件类型')) {
            return res.status(400).json({
                success: false,
                message: err.message
            });
        }
        
        // 传递其他错误给主错误处理中间件
        next(err);
    }
}; 